package com.example.app.ui.chat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.app.R;
import com.example.app.adapter.ChatAdapter;
import com.example.app.model.ChatMessage;

/**
 * 聊天页面Fragment
 * 用于显示聊天界面
 */
public class ChatFragment extends Fragment {
    private static final String TAG = "ChatFragment";
    private RecyclerView chatRecyclerView;
    private ChatAdapter chatAdapter;
    private BroadcastReceiver transcriptionResultReceiver;
    private ChatViewModel chatViewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "ChatFragment onCreate");

        // 初始化ViewModel
        chatViewModel = new ViewModelProvider(requireActivity()).get(ChatViewModel.class);

        // 初始化消息列表
        chatAdapter = new ChatAdapter(chatViewModel.getMessagesLiveData());

        // 观察消息列表变化
        chatViewModel.getMessagesLiveData().observe(this, messages -> {
            Log.d(TAG, "消息列表更新，当前消息数量: " + messages.size());
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
                if (chatRecyclerView != null && messages.size() > 0) {
                    chatRecyclerView.post(() -> {
                        chatRecyclerView.smoothScrollToPosition(messages.size() - 1);
                        Log.d(TAG, "已滚动到最新消息");
                    });
                }
            }
        });
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat, container, false);
        chatRecyclerView = view.findViewById(R.id.chatRecyclerView);
        chatRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        chatRecyclerView.setAdapter(chatAdapter);

        // 初始化时滚动到最后一条消息
        if (chatViewModel.getMessagesLiveData().getValue() != null && chatViewModel.getMessagesLiveData().getValue().size() > 0) {
            chatRecyclerView.post(() -> chatRecyclerView.smoothScrollToPosition(chatViewModel.getMessagesLiveData().getValue().size() - 1));
        }

        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "ChatFragment onResume");
        registerReceiver();
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver();
    }

    private void registerReceiver() {
        if (transcriptionResultReceiver == null) {
            transcriptionResultReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    if ("com.example.app.AUDIO_TRANSCRIPTION_RESULT".equals(intent.getAction())) {
                        String result = intent.getStringExtra("transcription_result");
                        Log.d(TAG, "收到广播: " + intent.getAction());
                        Log.d(TAG, "转写结果: " + result);
                        handleTranscriptionResult(result);
                    }
                }
            };
        }
        LocalBroadcastManager.getInstance(requireContext())
                .registerReceiver(transcriptionResultReceiver, new IntentFilter("com.example.app.AUDIO_TRANSCRIPTION_RESULT"));
        Log.d(TAG, "广播接收器已注册");
    }

    private void unregisterReceiver() {
        if (transcriptionResultReceiver != null) {
            LocalBroadcastManager.getInstance(requireContext()).unregisterReceiver(transcriptionResultReceiver);
            transcriptionResultReceiver = null;
            Log.d(TAG, "广播接收器已注销");
        }
    }

    private void handleTranscriptionResult(String result) {
        if (result != null && !result.isEmpty()) {
            Log.d(TAG, "开始处理转写结果");

            // 由于消息已经在 ConnectFragment 中添加，这里只需要刷新界面
            if (chatAdapter != null) {
                chatAdapter.notifyDataSetChanged();
                Log.d(TAG, "已通知适配器更新");

                // 滚动到最新消息
                if (chatViewModel.getMessagesLiveData().getValue() != null) {
                    chatRecyclerView.post(() -> {
                        chatRecyclerView.smoothScrollToPosition(chatViewModel.getMessagesLiveData().getValue().size() - 1);
                        Log.d(TAG, "已滚动到最新消息");
                    });
                }
            }
        }
    }

    private void addMessage(ChatMessage message) {
        Log.d(TAG, "addMessage: 添加新消息 - 内容: " + message.getContent() + ", 类型: " + message.getType());
        chatViewModel.addMessage(message);
        Log.d(TAG, "addMessage: 消息已添加到列表，当前消息数量: " + chatViewModel.getMessagesLiveData().getValue().size());

        if (chatAdapter != null) {
            chatAdapter.notifyItemInserted(chatViewModel.getMessagesLiveData().getValue().size() - 1);
            Log.d(TAG, "addMessage: 已通知适配器更新");

            // 滚动到最新消息
            chatRecyclerView.post(() -> {
                chatRecyclerView.smoothScrollToPosition(chatViewModel.getMessagesLiveData().getValue().size() - 1);
                Log.d(TAG, "addMessage: 已滚动到最新消息");
            });
        }
    }
} 